//vue的data
var _Global_Data = {

    query_info: {

        from: '',

        to: ''

    },

    customer_lists: [],     //客户列表

    customer_id: '',       //客户id

    user_summary_list: {},     //用户数据变化总表

    user_source_map: {

        0: '其他',

        1: '公众号搜索',

        17: '名片分享',

        30: '扫描二维码',

        43: '图文页右上角菜单',

        51: '支付后关注',

        57: '图文页内公众号名称',

        75: '公众号文章广告',

        78: '朋友圈广告'

    },                          //用户类别映射表

    admin_level : 1,            //用户权限级别

    user_count : 0,             //微信用户量

    myChart : {},               //柱图

    pieChart : {},　            //饼图

    user_source: [],           //本地存储的用户类别数组

    time_object: [],           //本地存储的时间数组

    new_attention: [],      //本地存储的新增用户关注量

    cancel_attention: [],      //本地存储的减少用户关注量

    attention_detail: [],      //用户数据变化详情

    total_attention: []          //本地存储的总用户量

};

var WechatResource = new Resource(API_LIST.WECHAT_DATA, Vue.http);

var CreateResource = new Resource(API_LIST.GENERAL_SUB, Vue.http);

var WechatUserResource = new Resource(API_LIST.WECHAT_USER, Vue.http);


!function machineInfo() {

    var vm = new Vue({

        el: '#wechat_table',

        data: _Global_Data,

        created: function () {

            this.initData();

        },

        updated: function(){

            $('.customer').val(this.customer_id).trigger('change');

        },

        computed: {},

        methods: {
            //select2获取value的方法
            getValue: function getValue(e) {

                this[e.target.dataset.name] = e.target.value;

            },
            //清空日期的方法
            resetTime: function resetTime(id) {

                this.$refs[id].value = '';

            },
            //生成柱状图
            setBarEchart: function setEchart() {

                var self = this;

                var option = {
                    title: {
                        text: '微信公众号数据统计'
                    },
                    tooltip: {},
                    legend: {
                        data: ['订阅量', '取关量', '剩余总量']
                    },
                    xAxis: {
                        data: self.time_object
                    },
                    yAxis: {},
                    series: [
                        {
                            name: '订阅量',
                            type: 'bar',
                            data: self.new_attention
                        },
                        {
                            name: '取关量',
                            type: 'bar',
                            data: self.cancel_attention
                        },
                        {
                            name: '剩余总量',
                            type: 'bar',
                            data: self.total_attention
                        }]
                };

                this.myChart.setOption(option);

                this.myChart.on('click', function (params) {

                    self.dataTypeJudge(params);

                })

            },
            //生成饼状图
            createPieEchart: function createPieEchart(time, title) {

                var option = {
                    title: {
                        text: title + '(' + time + ')',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: this.user_source
                    },
                    series: [
                        {
                            name: '用户来源',
                            type: 'pie',
                            radius: '55%',
                            center: ['60%', '60%'],
                            data: this.attention_detail,
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };

                this.pieChart.setOption(option);

            },
            //生成饼图第一步，判断属于哪个类型的数据
            dataTypeJudge: function dataTypeJudge(params) {

                this.user_source.splice(0, this.user_source.length);

                this.attention_detail.splice(0, this.attention_detail.length);

                if (params.seriesName != '剩余总量') {

                    if (params.seriesName == '订阅量') {

                        this.createDetailObject(this.user_summary_list[params.name], 'new_user');

                        this.createPieEchart(params.name, '微信用户订阅来源');

                    } else {

                        this.createDetailObject(this.user_summary_list[params.name], 'cancel_user');

                        this.createPieEchart(params.name, '微信用户取关来源');

                    }

                }

            },
            //点击确认的方法
            confirmSearch: function confirmSearch() {

                this.query_info.from = this.$refs.startTime.value;

                this.query_info.to = this.$refs.endTime.value;

                this.queryData(this.query_info);

            },
            //生成订阅量和取关量本地数组的方法
            createSummaryObject: function createSummaryObject(object) {

                var self = this;

                for (var key in object) {

                    var new_user = 0;

                    var cancel_user = 0;

                    object[key].forEach(function (e) {

                        new_user += parseInt(e.new_user);

                        cancel_user += parseInt(e.cancel_user);

                    });

                    self.new_attention.push(new_user);

                    self.cancel_attention.push(cancel_user);

                }

            },
            //生成当前剩余总量数组
            createCumulateObject: function createCumulateObject(object) {

                var self = this;

                object.forEach(function (e) {

                    self.total_attention.push(e.cumulate_user);

                })

            },
            //生成饼图第二步，生成用户类别，类别以及对应订阅量和取关量的数组
            createDetailObject: function createSourceObject(object, type) {

                var self = this;

                object.forEach(function (e) {

                    if (e[type] != 0) {

                        var data = {

                            value: e[type],

                            name: self.user_source_map[e.user_source]

                        };

                        self.user_source.push(self.user_source_map[e.user_source]);

                        self.attention_detail.push(data);

                    }

                })

            },
            //清空原有数组
            clearObject: function clearObject() {

                this.new_attention.splice(0, this.new_attention.length);

                this.cancel_attention.splice(0, this.cancel_attention.length);

                this.total_attention.splice(0, this.total_attention.length);

            },
            //初始化时间
            initTime : function initTime(){

                var current_Date = new Date();

                current_Date.setDate(current_Date.getDate()-1);

                var end_time = current_Date.toLocaleDateString();

                end_time = end_time.replace(/\//g,'-');

                current_Date.setDate(current_Date.getDate()-5);

                var start_time = current_Date.toLocaleDateString();

                start_time = start_time.replace(/\//g,'-');

                this.$refs.startTime.value = start_time;

                this.query_info.from = start_time;

                this.$refs.endTime.value = end_time;

                this.query_info.to = end_time;

            },
            //初始化得到相关数据
            queryData: function initData(params) {

                var self = this;

                self.clearObject();

                App.blockUI('#query_form');

                WechatResource.show(self.customer_id, params)
                    .then(function (res) {

                        if (parseInt(res.data.code) === 0) {

                            self.user_summary_list = res.data.user_summary.list;

                            self.time_object = Object.keys(res.data.user_summary.list);

                            self.createSummaryObject(res.data.user_summary.list);

                            self.createCumulateObject(res.data.user_cumulate.list);

                            self.setBarEchart();

                        } else {

                            alert(res.data.error);

                        }

                        App.unblockUI('#query_form');

                    })
                    .catch(function (err) {

                        console.log(err);

                        App.unblockUI('#query_form');

                        alert('网络异常，请重试！');

                    })

            },
            //获取初始数据
            initData: function initData() {

                var self = this;

                return WechatUserResource.create()
                                    .then(function (res) {

                                        if (parseInt(res.data.code) === 0) {

                                            self.user_count = res.data.wechat_user_info.user_count;

                                            self.admin_level = res.data.subordinates.admin_level;

                                            if( parseInt(res.data.subordinates.admin_level) === 1 ){

                                                self.customer_lists = res.data.subordinates.customers;

                                                self.customer_id = res.data.subordinates.customers[0].id;

                                            }else {

                                                self.customer_id = res.data.subordinates.customer_id;

                                            }

                                            self.initTime();

                                            //初始化echart
                                            self.myChart = echarts.init(document.getElementById('histogram'));
                                            //初始化第二个echart
                                            self.pieChart = echarts.init(document.getElementById('pie_chart'));

                                            self.queryData(self.query_info);

                                        } else {

                                            alert(res.data.error);

                                        }

                                    })
                                    .catch(function (err) {

                                        console.log(err);

                                        alert('网络异常，请重试！');

                                    })

            }

        }

    })

}();
